import { Button, Input, message, Upload, Spin, Divider, Icon, Select, Modal, Alert} from "antd";
import React, { Component } from "react";
import "../css/schoolinfoeditor.css";
import { PlusOutlined, FormOutlined} from "@ant-design/icons";
import {updateSchoolProfilesApi, uploadSchoolImgApi, addSchoolImgApi, getSchoolProfilesAndImgAndSchoolLevelApi, deleteSchoolImgApi, unloadSchoolImgApi, updateSchoolLevelApi} from "../js/api.js"
import { iconFontUrl, } from "../js/config.js";

const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,

});

class SchoolInfoEditor extends Component{
    constructor(){
        super()
        this.state={
            schoolLevel:"",        //学校类型
            profiles:"",    //学校简介
            imgList:[],     //学校图片列表，用于Upload组件
            spinning:true,      //加载状态
            schoolLevelIsUse:false,      //类型是否可编辑
            profilesIsUse:false,     //简介是否可编辑
            previewImg:"",       //预览的图片url
            previewOpen:false,      //预览图片窗口控制
            previewTitle:""     //图片预览标题
        }
    }

    componentDidMount(){
        this.refreshData();
    }

    //学校简介和图片路径获取
    refreshData=()=>{
        const schoolId = sessionStorage.getItem("departmentId");
        //学校简介和图片路径获取
        getSchoolProfilesAndImgAndSchoolLevelApi(schoolId)
            .then(res=>{
                if(res.data){
                    //避免img为null时方法调用报错
                    if(res.data.img){
                        //数据库存储多个图片时各路径之间以逗号分隔
                        let List=res.data.img.split(",")
                        //赋值imgList用于Upload组件
                        let imgList=List.filter(element=>element!="").map((element, index) => {
                            return{
                                //从路径中获取图片名字
                                name:element.split("/").length>3?element.split("/")[2]+"/"+element.split("/")[3]:element.split("/")[2],    
                                uid:index,
                                status:"done",
                                url:"https://tidu-hangzhou.oss-cn-hangzhou.aliyuncs.com/schoolImg/"+element.split("/")[2]
                            }
                        });
                        this.setState({
                            schoolLevel:res.data.schoolLevel,
                            profiles:res.data.profiles,
                            imgList,
                            spinning:false  //终止加载状态
                        })
                    }
                    else{
                        this.setState({
                            schoolLevel:res.data.schoolLevel,
                            profiles:res.data.profiles,
                            spinning:false  //终止加载状态
                        })
                    }
                }
            })
    }

    //多行文本的输入绑定
    onTextareaChange=(e)=>{
        this.setState({
            profiles:e.target.value
        })
    }   

    //学校类型更新
    updateSchoolLevel=()=>{    
        //加载状态
        this.setState({
            spinning:true
        })
        const schoolId = sessionStorage.getItem("departmentId");
        //学校类型更新
        updateSchoolLevelApi({id:schoolId, schoolLevel:this.state.schoolLevel})
            .then(res=>{
                if(res.data=="success"){
                    this.setState({
                        spinning:false,
                        schoolLevelIsUse:false
                    })
                    message.success("保存成功");
                }
                else {
                    this.setState({
                        spinning:false
                    })
                    message.error("保存失败");
                }
            })
    }

    //学校简介更新
    updateProfiles=()=>{
        //加载状态
        this.setState({
            spinning:true
        })
        const schoolId = sessionStorage.getItem("departmentId");
        //学校简介更新
        updateSchoolProfilesApi({id:schoolId, profiles:this.state.profiles})
            .then(res=>{
                if(res.data=="success"){
                    this.setState({
                        spinning:false,
                        profilesIsUse:false
                    })
                    message.success("保存成功");
                }
                else {
                    this.setState({
                        spinning:false
                    })
                    message.error("保存失败");
                }
            })
    }

    //图片预览
    imgPreview=(img)=>{
        console.log(img);
        this.setState({
            previewImg:img.url,
            previewOpen:true,
            previewTitle:img.name
        })
    }

    //取消图片预览
    previewCancel=()=>{
        this.setState({
            previewImg:"",
            previewOpen:false,
            previewTitle:""
        })
    }

    //Upload组件的change事件回调，包括图片上传和删除
    imgListChange=(e)=>{
        //加载状态
        this.setState({
            spinning:true
        })
        const schoolId = sessionStorage.getItem("departmentId");
        //当e.fileList包含e.file时为图片上传
        if(e.fileList.find(file=>file.uid===e.file.uid)){
            //限制文件类型
            if(e.file.type.includes("jpeg")||e.file.type.includes("jpg")||e.file.type.includes("png")){
                const file = new FormData();
                file.append("file", e.file);
                //上传图片（阿里云服务器）
                uploadSchoolImgApi(file)
                    .then(res=>{
                        if(res.data!="fail"){
                            //图片路径存储（数据库）
                            //res.data为图片路径
                            addSchoolImgApi({id:schoolId, img:res.data})
                                .then(res2=>{
                                    if(res2.data=="success"){
                                        //更新数据
                                        this.refreshData();
                                        message.success("上传成功");
                                    }  
                                    else{
                                        this.setState({
                                            spinning:false
                                        })
                                        message.error("上传失败");  
                                    }  
                                })
                        }
                        else{
                            this.setState({
                                spinning:false
                            })
                            message.error("上传失败");
                        }
                    })
            }
            else{
                this.setState({
                    spinning:false
                })
                message.warning("仅限上传jpg、jpeg和png格式图片")
            }
        }
        //当e.fileList不包含e.file时为图片删除
        else{
            //删除图片路径（数据库）
            deleteSchoolImgApi({id:schoolId, img:"/schoolImg/"+e.file.name })
                .then(res=>{
                    if(res.data=="success"){
                        //删除图片（阿里云服务器）
                        unloadSchoolImgApi({filename:e.file.name})
                            .then(res2=>{
                            })
                        //更新数据
                        this.refreshData();
                        message.success("删除成功")
                    } 
                    else{
                        this.setState({
                            spinning:false
                        })
                        message.error("删除失败");
                    }
                })
        }
    }

    //图片上传的显示组件
    uploadButton =()=>{
        return(
            <div>
                <PlusOutlined style={{ fontSize:"23px" }}/>
                <div style={{marginTop: 8}}>
                    图片上传
                </div>
            </div>
        )
    }

    render(){
        return(
            <div className="schoolInfo-container">
                <Spin 
                    spinning={this.state.spinning}
                >
                    <div className="schoolInfo-title">
                        <IconFont type="icon-xuexiao" className='icon' style={{fontSize:"24px", marginRight:"5px"}}></IconFont>
                            学校信息</div>
                    <Divider style={{marginBottom:"5px", fontWeight:"200", fontSize:"18px", color:"gray"}} dashed plain>信息编辑</Divider>
                    {/* 学校类型 */}
                    <div className="schoolInfo-item-container">
                        <div className="schoolInfo-item-header">
                            <div className="schoolInfo-item-title-tag">
                            </div>
                            <div className="schoolInfo-item-title">
                                <span>
                                学校类型
                                </span>
                            </div> 
                            <div className="schoolInfo-item-button-editor">
                                
                                {   
                                    this.state.schoolLevelIsUse?
                                        <div style={{height:"32px"}}></div>
                                        :<Button   style={{padding:0, border:"none", boxShadow:"none"}} onClick={()=>this.setState({schoolLevelIsUse:true})}><FormOutlined /></Button>
                                }
                            </div>
                        </div>
                        <div className="schoolInfo-item-content">
                            <Select
                                value={this.state.schoolLevel}
                                style={{
                                    width: "15vw",
                                }}
                                disabled={!this.state.schoolLevelIsUse}
                                onChange={value=>{this.setState({schoolLevel:value})}}
                            >
                                <Option value="高中">高中</Option>
                                <Option value="初中">初中</Option>
                                <Option value="小学">小学</Option>
                                <Option value="幼儿园">幼儿园</Option>
                            </Select>
                            <div style={{display:"inline-block", marginLeft:"6px"}}>
                                {   
                                    this.state.schoolLevelIsUse?
                                        <Button   type="primary" onClick={this.updateSchoolLevel}>保存</Button>
                                        : null
                                }
                            </div>
                        </div>
                    </div>
                    {/* 学校简介 */}
                    <div className="schoolInfo-item-container" style={{paddingTop:"10px"}}>
                        <div className="schoolInfo-item-header">
                            <div className="schoolInfo-item-title-tag">
                            </div>
                            <div className="schoolInfo-item-title">
                                学校简介
                            </div>
                            <div className={this.state.profilesIsUse?"schoolInfo-item-button-save":"schoolInfo-item-button-editor"}>
                                
                                {   
                                    this.state.profilesIsUse?
                                        <Button   type="primary" onClick={this.updateProfiles}>保存</Button>
                                        :<Button   style={{padding:0, border:"none", boxShadow:"none"}} onClick={()=>this.setState({profilesIsUse:true})}><FormOutlined /></Button>
                                }
                            </div>
                        </div>
                        <div className="schoolInfo-item-content" style={{marginTop:"1vh"}}>
                            <Input.TextArea 
                                style={{fontSize:"30px"}}
                                allowClear 
                                autosize={{ minRows: 9}} 
                                value={this.state.profiles} 
                                onChange={this.onTextareaChange} 
                                disabled={!this.state.profilesIsUse}
                            />
                        </div>  
                    </div>
                    {/* 学校图片 */}
                    <div className="schoolInfo-item-container">
                        <div className="schoolInfo-item-header">
                            <div className="schoolInfo-item-title-tag">
                            </div>
                            <div className="schoolInfo-item-title">
                                <span>
                                学校图片
                                </span>
                            </div>     
                        </div>
                        <div className="schoolInfo-item-content">
                            <Alert message="请您上传的图片尽量小于3M,图片过大可能会导致上传失败" type="info" showIcon style={{width:"420px", margin:"0 0 20px 0"}}/>
                            <Upload
                                //避免change事件多次触发
                                beforeUpload={()=>false}    
                                listType="picture-card"
                                fileList={this.state.imgList}
                                onPreview={this.imgPreview}
                                onChange={this.imgListChange}
                                style={{width:"30vw", height:"30vw"}}
                            >
                                {(this.state.imgList&&this.state.imgList.length >= 8) ? null : this.uploadButton()}
                            </Upload>
                            <Modal visible={this.state.previewOpen} title={this.state.previewTitle} footer={null} onCancel={this.previewCancel}>
                                <img
                                    style={{
                                        width: '100%',
                                    }}
                                    src={this.state.previewImg}
                                />
                            </Modal>
                        </div>
                    </div>
                </Spin>
            </div>
        )
    }
}

export  {SchoolInfoEditor};